const app = getApp();
Page({
  data:{
    state:false,
    openIt:false,
    nowText: '全部',
    nowText2:'全部',
    today:'',
    dayBefore:'',
    yearBefore:'',
    date1: '',
    date2:'',
    billType:null,
    now:1,
    nowD:1,
    styleNow:'box-rh',
    list:[],
    pageindex:1,
    pagesize:10,
    searchloading:false,
    searchloadingcomplete:false,
    teamloading: false,
    teamloadingcomplete:false,
    piloading: false,
    piloadingcomplete: false,
    isfromsearch:true,  //用于检测list是不是空的
    listnormal:false,

    currentTab:0,//tab
    teamList:[],
    teamCon:null,
    teamListPer:[],

    piList:[],

    intuandui:true,
    myTouxiang: app.globalData.baseInfo.profilePicturePath,
  },
  // filter筛选
  openFilter:function(){
    this.setData({
      openIt:!this.data.openIt,
      gogo:true
    })
  },

  //kwq
  clickTab: function (e) {
    var that = this;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      // console.log(e.target.dataset.current)
      that.setData({
        currentTab: e.target.dataset.current
      })
      if (e.target.dataset.current == 0){
        this.loadInfo();
        that.setData({
          teamList: [],
          piList: [],
        })
        wx.pageScrollTo({
          scrollTop: 0,
          duration: 0
        })
        if(that.data.list >10){
          that.setData({
            searchloading: true
          })
        }
      }
      if (e.target.dataset.current == 1){
        that.setData({
          teamList: [],
        })
        this.teamlist()
        // if (that.data.teamList >= 10) {
         
        // }
      }else if(e.target.dataset.current == 2){
        that.setData({
          piList: [],
        })
        this.pilist()
        // if (that.data.piList >= 10) {
        //   that.setData({
        //     piloading: true
        //   })
        // }
      }
    }
  },
  teamlist(pageIndex){
    var that = this;
    // this.teamDor(3)
    that.setData({
      piList: [],
      
      pageindex: 1,
      searchloading: false,
      searchloadingcomplete: false,
      teamloading: false,
      teamloadingcomplete: false,
      piloading: false,
      piloadingcomplete: false,
      listnormal:false
    })
    wx.request({
      url: app.globalData.path + 'services/app/applets/GetBatchTransferBills',
      data: {
        transferType: 3,
        pageIndex: pageIndex
      },
      method: 'POST',
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': 'Bearer ' + app.globalData.authorization
      },
      success: function (res) {
        var arr = res.data.result.items
        
        if (res.data.result.totalCount > 10) {
          console.log("111")
          that.setData({
            teamloading: true,
             teamloadingcomplete: false
          })
        }
        if (arr.length == 0) {
          that.setData({
            listnormal: true
          })
          return
        } else if (arr.length < 10){
          that.setData({
            teamloading: false,
            teamloadingcomplete:true
          })
        }else{
          that.setData({
            listnormal: false
          })
        }

        
        for (var i = 0; i < arr.length; i++) {
          arr[i].state = false
          
        }
        var arr = that.data.teamList.concat(arr)
        that.setData({

          teamList: arr
        })
        console.log(that.data.teamList)
      }
    })
  },
  pilist(pageIndex){
    var that = this;
    that.setData({
      teamList: [],
      // piList: [],
      pageindex: 1,
      searchloading: false,
      searchloadingcomplete: false,
      teamloading: false,
      teamloadingcomplete: false,
      piloading: false,
      piloadingcomplete: false,
      listnormal: false
    })
    // this.teamDor(2)
    wx.request({
      url: app.globalData.path + 'services/app/applets/GetBatchTransferBills',
      data: {
        transferType: 2,
        pageIndex: pageIndex
      },
      method: 'POST',
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': 'Bearer ' + app.globalData.authorization
      },
      success: function (res) {
        var arr = res.data.result.items
        if (res.data.result.totalCount > 10) {
          console.log("111")
          that.setData({
            piloading: true,
              piloadingcomplete: false
          })
        }
        if (arr.length == 0) {
          that.setData({
            listnormal: true
          })
          return
        } else if (arr.length < 10) {
          that.setData({
            piloading: false,
            piloadingcomplete:true
          })
        } else {
          that.setData({
            listnormal: false
          })
        }

        for (var i = 0; i < arr.length; i++) {
          arr[i].state = false
        }
        var arr = that.data.piList.concat(arr)
        that.setData({
          piList: arr
        })
      }
    })
  },
  teamInfo(e){
    var idx = parseInt(e.currentTarget.id);
    var arr = this.data.teamList;
    
    console.log(this.data.teamList[idx])
    // return
    var that = this
    wx.request({
      url: app.globalData.path + 'services/app/applets/GetBatchTeamPayBillDetail',
      data: {
        batchId: e.currentTarget.dataset.id,
      },
      method: 'POST',
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': 'Bearer ' + app.globalData.authorization
      },
      success: function (res) {
        
        var items = res.data.result.items;
       
        for(var i=0;i<items.length;i++){
          items[i].after = items[i].money - items[i].actionMoney
        }
        
        items.forEach(item => {
          item.money = that.numFilter(item.money) ,
          item.actionMoney = that.numFilter(item.actionMoney),
          item.after = item.after.toFixed(2),
            item.tax = that.numFilter(item.tax),
            item.poundage = that.numFilter(item.poundage)

        })
        //kwq
        that.data.teamList[idx].detail=items 
        // const _this = this;
        for (let i = 0; i < arr.length; i++) {
          if (i == idx) {
            arr[i].state = !arr[i].state;
            if (arr[i].state) {
              arr[i].styleNow = 'toRotate';
            } else {
              arr[i].styleNow = 'box-rh';
            }
          }
        }
        that.setData({
          teamList: arr
        })
        console.log(that.data.teamList)
      }
    })

  
  },
  piInfo(e){
    var idx = parseInt(e.currentTarget.id);
    console.log(idx);
    var arr = this.data.piList;
    console.log(e)
    var that = this
    wx.request({
      url: app.globalData.path + 'services/app/applets/GetBatchTransferBillDetail',
      data: {
        batchId: e.currentTarget.dataset.id,
      },
      method: 'POST',
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': 'Bearer ' + app.globalData.authorization
      },
      success: function (res) {
        var items = res.data.result.items;
        items.forEach(item => {
          item.money = that.numFilter(item.money),
            item.actionMoney = that.numFilter(item.actionMoney)
        })
        //kwq
        that.data.piList[idx].detail = items
        // const _this = this;
        for (let i = 0; i < arr.length; i++) {
          if (i == idx) {
            arr[i].state = !arr[i].state;
            if (arr[i].state) {
              arr[i].styleNow = 'toRotate';
            } else {
              arr[i].styleNow = 'box-rh';
            }
          }
        }
        that.setData({
          piList: arr
        })
      }
    })
   
  },
  // 日期
  changeDate1(e) {
    this.setData({ date1: e.detail.value.substr(0,10) });
  },
  changeDate2(e) {
    this.setData({ date2: e.detail.value.substr(0, 10) });
  },
  getToday(){
    var util = require('../../utils/util.js');
    var date = util.formatTime(new Date);
    var year = (new Date).getFullYear();
    var mon = (new Date).getMonth()+1-3;
    var day = (new Date).getDate();
    // console.log(date);
    // console.log(year);
    this.setData({
      today: date.substr(0, 10), dayBefore: year + '-0' + mon + '-' + day,
      yearBefore: year, date1: year+'-0'+mon+'-'+day, date2: date.substr(0, 10)})
    console.log(this.data.yearBefore);
    console.log(this.data.date1);
    console.log(this.data.date2);
  },
  // 选中
  toActive:function(e){
    if (e.currentTarget.dataset.index){
      this.setData({ now: e.currentTarget.dataset.index})
      if (e.currentTarget.dataset.index == 1){
        this.setData({ nowText: '全部', billType :null})
      } else if (e.currentTarget.dataset.index == 2) {
        this.setData({ nowText: '转入', billType: 0 })
      } else if (e.currentTarget.dataset.index == 3) {
        this.setData({ nowText: '提现', billType: 1 })
      } else if (e.currentTarget.dataset.index == 4) {
        this.setData({ nowText: '转出', billType: 2 })
      } else if (e.currentTarget.dataset.index == 5) {
        this.setData({ nowText: '打款', billType: 3 })
      } else if (e.currentTarget.dataset.index == 6) {
        this.setData({ nowText: '佣金发放', billType: 4 })
      } else if (e.currentTarget.dataset.index == 7) {
        this.setData({ nowText: '处理中', billType: 5 })
      }
    }
  },
  toActiveD: function (e) {
    const _this = this;
    this.getToday();
    if (e.currentTarget.dataset.index) {
      this.setData({ nowD: e.currentTarget.dataset.index })
      if (e.currentTarget.dataset.index == 1) {
        this.setData({ nowDText: '三个月' })
        var util = require('../../utils/util.js');
        var now = new Date();
        var mon = now.getMonth()+1-3;
        var year = now.getFullYear();
        var day = now.getDate();
        // var date = new Date(now.getTime() - 90 * 24 * 3600 * 1000);
        // var T1 = util.formatTime(date);
        var T1 = year+'-0'+mon+'-'+day;
        this.setData({
          date1: T1,
          date2: _this.data.today
        })
      } else if (e.currentTarget.dataset.index == 2) {
        this.setData({ nowDText: '近3天' })
        var util = require('../../utils/util.js');
        var now = new Date();
        var date = new Date(now.getTime() - 3 * 24 * 3600 * 1000);
        var T1 = util.formatTime(date);
        this.setData({
          date1: T1.substr(0,10),
          date2: this.data.today
        })
      } else if (e.currentTarget.dataset.index == 3) {
        this.setData({ nowDText: '近7天' })
        var util = require('../../utils/util.js');
        var now = new Date();
        var date = new Date(now.getTime() - 7 * 24 * 3600 * 1000);
        var T1 = util.formatTime(date);
        this.setData({
          date1: T1.substr(0, 10),
          date2: this.data.today
        })
      } else if (e.currentTarget.dataset.index == 4) {
        this.setData({ nowDText: '一个月' })
        var util = require('../../utils/util.js');
        var now = new Date();
        var date = new Date(now.getTime() - 30 * 24 * 3600 * 1000);
        var T1 = util.formatTime(date);
        this.setData({
          date1: T1.substr(0, 10),
          date2: this.data.today
        })
      }
    }
  },
  // 样式
  detailInfo:function(e){
    var idx = parseInt(e.currentTarget.id);
    console.log(idx);
    var arr = this.data.list;
    const _this = this;
    for(let i=0;i<arr.length;i++){
      if (i == idx) {
        arr[i].state = !arr[i].state;
        if(arr[i].state){
          arr[i].styleNow = 'toRotate';
        }else{
          arr[i].styleNow = 'box-rh';
        }
      }
    }
    _this.setData({
      list :arr
    })
  },
  onShow:function(){
    console.log('团队提现')
    console.log(this.data.myTouxiang)
    console.log(app.globalData.baseInfo.profilePicturePath)
    if (app.globalData.baseInfo.teamTransfer != true){
      this.setData({
        intuandui:true
      })
    }else{
      this.setData({
        intuandui: false
      })
    }
    this.loadInfo();
    this.setData({
      searchloading:false,
      searchloadingcomplete:false,
      pageindex:1,
      list:[],
      currentTab: 0,
      nowText2: '全部',
      isfromsearch:true,
      // dayBefore: '2018-01-01',
      yearBefore:'',
      billType:null,
      now: 1,
      nowD: 1,
      openIt:false,
      myTouxiang: app.globalData.baseInfo.profilePicturePath,
    })
  },
  onLoad:function(){
    this.loadInfo();
  },
  onHide:function(){
    this.setData({
      openIt: false,
    })
  },
  loadInfo(){
    const _this = this;
    _this.getToday();
    wx.request({
      url: app.globalData.path + 'services/app/applets/GetBills',
      data: {
        pageSize: 10,
        pageIndex: 1,
        beginDate: _this.data.dayBefore,
        endDate: _this.data.today,
      },
      method: 'POST',
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': 'Bearer ' + app.globalData.authorization
      },
      success: function (res) {
        console.log(res.data);
        if (res.statusCode == 401) {
          wx.removeStorage({
            key: 'token',
            success: function (res) {
            },
          })
          wx.reLaunch({
            url: '/pages/login/login'
          })
        }
        if (res.data.success) {
          let list = res.data.result.items;
          list.forEach(item => {
            // item.creationTime = item.creationTime.substr(0,10);
            item.money = _this.numFilter(item.money);
            item.balance = _this.numFilter(item.balance);
            item.state = false;
            item.styleNow = 'box-rh';
            item.creationTime = _this.handleDate(item.creationTime);
            if(item.summary){
              item.summary.in = _this.numFilter(item.summary.in);
              item.summary.out = _this.numFilter(item.summary.out);
              item.summary.putForward = _this.numFilter(item.summary.putForward);
            }
          })
          _this.setData({
            list: list,
            searchloading: true
          })
          if(list.length == 0){
            _this.setData({
              listnormal:true
            })
          }else{
            _this.setData({
              listnormal: false
            })
          }
        } else {
          wx.showToast({
            title: res.data.error.message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 处理日期
  handleDate:function(val){
    let a1 = val.split(' ')[0];
    let a2 = val.split(' ')[1];
    a1 = a1.substring(5, 10);
    a2 = a2.substring(0,5);
    // console.log(a1);
    // console.log(a2);
    if(this.getMD() == a1){
      return '今天 '+a2;
    }else if(this.getYe() == a1){
      return '昨天 '+a2;
    }else{
      return a1+' '+a2;
    }
  },
  // 今天
  getMD:function(){
    var util = require('../../utils/util.js');
    var now = new Date();
    var T1 = util.formatTime(now);
    let a1 = T1.split(' ')[0];
    // a1.substring(5, 10);
    return a1.substring(5, 10);
  },
  // 昨天
  getYe:function(){
    var util = require('../../utils/util.js');
    var now = new Date();
    var date = new Date(now.getTime() - 1 * 24 * 3600 * 1000);
    var T1 = util.formatTime(date);
    let a1 = T1.split(' ')[0];
    // a1.substring(5, 10);
    return a1.substring(5, 10);
  },
  // 请求
  listrequest:function(pageindex,callback){
    const _this = this;
    wx.request({
      url: app.globalData.path + 'services/app/applets/GetBills',
      data: {
        pageSize: 10,
        pageIndex: pageindex,
        beginDate: _this.data.dayBefore,
        endDate: _this.data.today,
        billType: _this.data.billType
      },
      method: 'POST',
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': 'Bearer ' + app.globalData.authorization
      },
      success: function (res) {
        console.log(res.data);
        if (res.statusCode == 401) {
          wx.removeStorage({
            key: 'token',
            success: function (res) {
            },
          })
          wx.reLaunch({
            url: '/pages/login/login'
          })
        }
        if (res.data.success) {
          callback(res.data.result);
        } else {
          wx.showToast({
            title: res.data.error.message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 请求后
  fetchlist:function(){
    const _this = this;
    console.log(this.data.pageindex)
    let pageindex = this.data.pageindex;
    _this.listrequest(pageindex,function(data){
      console.log(data);
      let list = data.items;
      list.forEach(item => {
        // item.creationTime = item.creationTime.substr(0, 10);
        item.money = _this.numFilter(item.money);
        item.balance = _this.numFilter(item.balance);
        item.state = false;
        item.styleNow = 'box-rh';
        item.creationTime = _this.handleDate(item.creationTime);
        if (item.summary) {
          item.summary.in = _this.numFilter(item.summary.in);
          item.summary.out = _this.numFilter(item.summary.out);
          item.summary.putForward = _this.numFilter(item.summary.putForward);
        }
      })
      if(data.items.length != 0){
        let arr = [];
        //如果isfromsearch是true从data中取出数据，否则先从原来的数据继续添加
        _this.data.isfromsearch ? arr = list : arr = _this.data.list.concat(list);
        _this.setData({
          list:arr,
          searchloading:true
        });
      }else{
        _this.setData({
          searchloading:false,
          searchloadingcomplete:true
        })
      }
    })
  },
  onReachBottom:function(){
    console.log('加载更多');
    
    const _this = this;


    if (this.data.currentTab== 0 ){
      if (_this.data.searchloading && !_this.data.searchloadingcomplete) {
        _this.setData({
          pageindex: _this.data.pageindex + 1,
          isfromsearch: false
        });
      }
      setTimeout(() => {
        _this.fetchlist();
      }, 500)
    } else if (this.data.currentTab == 1){
       if (_this.data.teamloading && !_this.data.teamloadingcomplete) {
          _this.setData({
            pageindex: _this.data.pageindex + 1,
          });
          console.log('加载下一页')
         
         _this.teamlist(this.data.pageindex)
        
      }
    }else{
      if (_this.data.piloading && !_this.data.piloadingcomplete) {
        _this.setData({
          pageindex: _this.data.pageindex + 1,
        });
        console.log('加载下一页')
        
          _this.pilist(this.data.pageindex)
     
      }
    }
   

   
    
  },
  // 过滤器
  numFilter:function(val) {
    // 截取当前数据到小数点后两位
    // let realVal = Number(val).toFixed(2)
    // num.toFixed(2)获取的是字符串
    // return Number(realVal)

    if (val || val == 0) {
      val = val.toString().replace(/\$|\,/g, '');
      if (isNaN(val)) {
        val = "0.00";
      }
      let sign = (val == (val = Math.abs(val)));
      val = Math.floor(val * 100 + 0.50000000001);
      let cents = val % 100;
      val = Math.floor(val / 100).toString();
      if (cents < 10) {
        cents = "0" + cents
      }
      for (var i = 0; i < Math.floor((val.length - (1 + i)) / 3); i++) {
        val = val.substring(0, val.length - (4 * i + 3)) + ',' + val.substring(val.length - (4 * i + 3));
      }
      return (((sign) ? '' : '-') + val + '.' + cents);
    }
  },
  // 取消
  cancel:function(){
    this.setData({
      openIt:false,
      // nowText2: '全部',
      // dayBefore: '2018-01-01',
      // today: this.data.today,
      now: 1,
      nowD:1,
      date1:'',
      date2:''
    })
  },
  // 确定
  sure:function(){
    const _this = this;
    this.setData({
      openIt: false,
      nowText2:this.data.nowText,
      dayBefore:this.data.date1,
      today:this.data.date2,
      pageindex:1
    })
    console.log(this.data.date1);
    console.log(this.data.date2);
    // if (_this.data.nowD == 1){
    //   _this.getToday();
    //   _this.setData({
    //     dayBefore: _this.data.yearBefore+'-01-01'
    //   })
    // }
    // console.log(_this.data.dayBefore);
    // console.log(_this.data.today);
    wx.request({
      url: app.globalData.path + 'services/app/applets/GetBills',
      data: {
        beginDate: _this.data.dayBefore,
        endDate: _this.data.today,
        billType: _this.data.billType,
        pageIndex: 1,
      },
      method: 'POST',
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': 'Bearer ' + app.globalData.authorization
      },
      success: function (res) {
        if (res.statusCode == 401) {
          wx.removeStorage({
            key: 'token',
            success: function (res) {
            },
          })
          wx.reLaunch({
            url: '/pages/login/login'
          })
        }
        if (res.data.success) {
          let list = res.data.result.items;
          list.forEach(item => {
            // item.creationTime = item.creationTime.substr(0,10);
            item.money = _this.numFilter(item.money);
            item.balance = _this.numFilter(item.balance);
            item.state = false;
            item.styleNow = 'box-rh';
            item.creationTime = _this.handleDate(item.creationTime);
            if (item.summary) {
              item.summary.in = _this.numFilter(item.summary.in);
              item.summary.out = _this.numFilter(item.summary.out);
              item.summary.putForward = _this.numFilter(item.summary.putForward);
            }
          })
          _this.setData({
            list: list,
          })
          if(list.length <= 10){
            _this.setData({
              searchloading: false,
              searchloadingcomplete: false
            })
          }else{
            _this.setData({
              searchloading: true,
              searchloadingcomplete: false
            })
          }
          if (list.length == 0) {
            _this.setData({
              listnormal: true
            })
          } else {
            _this.setData({
              listnormal: false
            })
          }
        } else {
          wx.showToast({
            title: res.data.error.message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 上拉刷新
  onPullDownRefresh() {
    console.log('--------下拉刷新-------')
    const _this = this;
    wx.showNavigationBarLoading() //在标题栏中显示加载
    // 账单列表
    wx.request({
      url: app.globalData.path + 'services/app/applets/GetBills',
      data: {
        beginDate: _this.data.dayBefore,
        endDate: _this.data.today,
        billType: _this.data.billType,
        pageIndex: 1,
      },
      method: 'POST',
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': 'Bearer ' + app.globalData.authorization
      },
      success: function (res) {
        console.log(res.data);
        if (res.statusCode == 401) {
          wx.removeStorage({
            key: 'token',
            success: function (res) {
            },
          })
          wx.reLaunch({
            url: '/pages/login/login'
          })
        }
        if (res.data.success) {
          let list = res.data.result.items;
          list.forEach(item => {
            // item.creationTime = item.creationTime.substr(0,10);
            item.money = _this.numFilter(item.money);
            item.balance = _this.numFilter(item.balance);
            item.state = false;
            item.styleNow = 'box-rh';
            item.creationTime = _this.handleDate(item.creationTime);
            if (item.summary) {
              item.summary.in = _this.numFilter(item.summary.in);
              item.summary.out = _this.numFilter(item.summary.out);
              item.summary.putForward = _this.numFilter(item.summary.putForward);
            }
          })
          _this.setData({
            list: list
          })
          if (list.length <= 10) {
            _this.setData({
              searchloading: false,
              searchloadingcomplete: false
            })
          } else {
            _this.setData({
              searchloading: true,
              searchloadingcomplete: false
            })
          }
          if (list.length == 0) {
            _this.setData({
              listnormal: true
            })
          } else {
            _this.setData({
              listnormal: false
            })
          }
        } else {
          wx.showToast({
            title: res.data.error.message,
            icon: 'none',
            duration: 2000
          })
        }
      },
      complete: function (res) {
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
      }
    })
  }
})